<template>
  <view class="wifi-list-container">
    <!-- 页面头部 -->
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <view class="back-icon">←</view>
      </view>
      <view class="header-title">{{ currentWifiName || '腾途传媒-5G' }}</view>
      <view class="header-icons">
        <view class="icon-item">•••</view>
        <view class="icon-item record-btn">⚪</view>
      </view>
    </view>
    
    <!-- WiFi信息展示区域 -->
    <view class="wifi-info-section" v-if="wifiList.length > 0">
      <view class="wifi-icon-area">
        <view class="wifi-signal-icon">📶</view>
        <view class="wifi-name-display">{{ wifiList[0].ssid }}</view>
      </view>
      
      <view class="wifi-actions-area">
        <!-- 复制密码按钮 -->
        <button 
          class="action-button copy-button" 
          @tap="copyPassword"
          v-if="wifiList[0].password"
        >
          复制密码
        </button>
        
        <!-- 一键连接按钮 -->
        <button 
          class="action-button connect-button"
          @tap="connectWifi(wifiList[0])"
          :disabled="connecting"
        >
          {{ connecting ? '连接中...' : '一键连接' }}
        </button>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-area" v-else-if="loading">
      <view class="loading-text">正在获取WiFi信息...</view>
    </view>
    
    <!-- 错误状态 -->
    <view class="error-area" v-else>
      <view class="error-text">暂未获取到WiFi信息</view>
      <view class="debug-info" v-if="showTestMode">
        <text>调试信息：</text>
        <text>设备ID: {{ deviceId }}</text>
        <text>API地址: {{ currentApiUrl }}</text>
      </view>
      <button class="retry-button" @tap="loadWifiList">重试</button>
    </view>
    
    <!-- 备注信息 -->
    <view class="note-area" v-if="wifiList.length > 0">
      <text>备注：</text>
    </view>
    
    <!-- 广告区域 -->
    <view class="ad-area" v-if="wifiList.length > 0">
      <view class="ad-content">
        <view class="ad-icon">🏨</view>
        <view class="ad-text">
          <view class="ad-title">去哪儿LAPP，惊喜折扣</view>
          <view class="ad-subtitle">嗨不停，机票酒店超...</view>
        </view>
        <view class="ad-brand">去哪儿旅行</view>
      </view>
    </view>
  </view>
</template>

<script>
import { getWifiList } from '@/api/wifi/auth'

export default {
  name: 'WifiList',
  data() {
    return {
      deviceId: '',
      sessionId: '',
      currentWifiName: '',
      showList: false,
      wifiList: [],
      loading: false,
      connecting: false,
      selectedWifi: null,
      showTestMode: true, // 显示调试信息
      currentApiUrl: '', // 当前API地址
      isIOS: false // 是否为iOS系统
    }
  },
  onLoad(options) {
    console.log('WiFi列表页参数：', options)
    
    // 检测系统平台
    const systemInfo = uni.getSystemInfoSync()
    this.isIOS = systemInfo.platform === 'ios'
    console.log('当前系统平台：', systemInfo.platform, '是否为iOS：', this.isIOS)
    
    // 显示当前API配置用于调试
    const config = require('@/config')
    console.log('当前API地址：', config.baseUrl)
    console.log('完整API URL：', `${config.baseUrl}/device/wifi/${options.deviceId || ''}`)
    
    this.deviceId = options.deviceId || ''
    this.sessionId = options.sessionId || ''
    this.currentApiUrl = config.baseUrl // 设置当前API地址用于显示
    
    // 判断是否从主页直接跳转过来
    const isDirect = options.direct === 'true'
    
    if (!this.deviceId) {
      uni.showToast({
        title: '参数错误',
        icon: 'error'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    // 如果是直接跳转，立即加载WiFi列表并显示
    if (isDirect) {
      this.loadWifiList()
    } else if (!this.sessionId) {
      uni.showToast({
        title: '会话参数错误',
        icon: 'error'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    } else {
      // 原有逻辑：自动加载WiFi列表
      this.loadWifiList()
    }
  },
  
  // 分享给好友
  onShareAppMessage(res) {
    console.log('WiFi列表页分享给好友', res)
    
    const wifiName = this.wifiList.length > 0 ? this.wifiList[0].ssid : this.currentWifiName
    
    return {
      title: `免费WiFi - ${wifiName}，一键连接`,
      path: `/pages/index?deviceId=${this.deviceId}`,
      imageUrl: '' // 可以设置分享图片
    }
  },
  
  // 分享到朋友圈
  onShareTimeline() {
    console.log('WiFi列表页分享到朋友圈')
    
    const wifiName = this.wifiList.length > 0 ? this.wifiList[0].ssid : this.currentWifiName
    
    return {
      title: `免费WiFi - ${wifiName}，一键连接`,
      query: `deviceId=${this.deviceId}`,
      imageUrl: ''
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 显示WiFi列表
    showWifiList() {
      this.showList = true
      if (this.wifiList.length === 0) {
        this.loadWifiList()
      }
    },
    
    // 加载WiFi列表
    async loadWifiList() {
      if (this.loading) return
      
      try {
        this.loading = true
        uni.showLoading({ title: '获取WiFi列表...' })
        
        console.log('正在调用WiFi信息API，deviceId：', this.deviceId)
        const response = await getWifiList(this.deviceId)
        console.log('WiFi信息API响应：', response)
        
        if (response.code === 200 && response.data) {
          // 后端返回的是单个设备的WiFi信息，转换为列表格式
          const wifiData = response.data
          this.wifiList = [{
            ssid: wifiData.ssid || '未知WiFi',
            password: wifiData.password || '',
            isSecure: wifiData.isSecure !== false,
            securityType: wifiData.securityType,
            frequency: wifiData.frequency,
            signalStrength: wifiData.signalStrength
          }]
          
          // 如果设备名称存在，更新当前WiFi名称
          if (wifiData.deviceName) {
            this.currentWifiName = wifiData.deviceName
          } else if (wifiData.ssid) {
            this.currentWifiName = wifiData.ssid
          }
          
          console.log('WiFi信息加载成功：', this.wifiList[0])
        } else {
          throw new Error(response.msg || '获取WiFi信息失败')
        }
      } catch (error) {
        console.error('加载WiFi列表失败，详细错误：', error)
        console.error('错误类型：', typeof error)
        console.error('错误堆栈：', error.stack)
        
        // 显示详细的错误信息
        let errorMessage = '获取WiFi列表失败'
        if (error.response) {
          console.error('API响应错误：', error.response)
          errorMessage = `API错误: ${error.response.status} - ${error.response.data?.msg || error.response.statusText}`
        } else if (error.request) {
          console.error('网络请求错误：', error.request)
          errorMessage = '网络连接失败，请检查网络设置'
        } else {
          console.error('其他错误：', error.message)
          errorMessage = error.message || '未知错误'
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'error',
          duration: 3000
        })
        
        // 不再使用模拟数据，让用户看到真实的错误状态
        this.wifiList = []
      } finally {
        this.loading = false
        uni.hideLoading()
      }
    },
    
    // 刷新WiFi列表
    refreshWifiList() {
      this.loadWifiList()
    },
    
    // 选择WiFi
    selectWifi(wifi) {
      this.selectedWifi = wifi
      this.connectWifi(wifi)
    },
    
    // 连接WiFi
    async connectWifi(wifi) {
      if (this.connecting) return
      
      try {
        this.connecting = true
        this.selectedWifi = wifi
        
        uni.showLoading({ title: '正在连接WiFi...' })
        
        // iOS和Android都尝试自动连接（iOS需要11及以上版本支持）
        await this.connectToWifi(wifi.ssid, wifi.password)
        
        uni.hideLoading()
        uni.showToast({
          title: `已成功连接到 ${wifi.ssid}`,
          icon: 'success'
        })
        
        // 连接成功后，等待2秒然后跳转到手机验证页面
        setTimeout(() => {
          this.gotoPhoneVerification()
        }, 2000)
        
      } catch (error) {
        console.error('连接WiFi失败：', error)
        uni.hideLoading()
        
        // 连接失败时的处理 - 提供手动连接选项
        const errorMsg = this.isIOS 
          ? `自动连接失败。iOS系统需要iOS 11及以上版本才能自动连接WiFi。\n\nWiFi名称：${wifi.ssid}\n密码：${wifi.password}\n\n建议您手动连接WiFi后继续操作。`
          : `自动连接WiFi失败。\n\nWiFi名称：${wifi.ssid}\n密码：${wifi.password}\n\n建议您手动连接WiFi后继续操作。`
        
        uni.showModal({
          title: '连接失败',
          content: errorMsg,
          confirmText: '复制密码',
          cancelText: '继续认证',
          success: (res) => {
            if (res.confirm) {
              this.copyPassword()
              // 复制密码后给出操作指引
              setTimeout(() => {
                uni.showModal({
                  title: '连接指引',
                  content: '密码已复制！\n\n请按以下步骤操作：\n1. 打开手机系统设置\n2. 进入WiFi设置\n3. 选择WiFi并粘贴密码\n4. 连接成功后返回小程序',
                  showCancel: false,
                  confirmText: '继续认证',
                  success: () => {
                    this.gotoPhoneVerification()
                  }
                })
              }, 500)
            } else {
              // 允许用户继续流程
              this.gotoPhoneVerification()
            }
          }
        })
      } finally {
        this.connecting = false
      }
    },
    
    // 使用微信小程序API连接WiFi（符合官方文档规范）
    connectToWifi(ssid, password) {
      return new Promise((resolve, reject) => {
        console.log(`开始连接WiFi - SSID: ${ssid}, 平台: ${this.isIOS ? 'iOS' : 'Android'}`)
        
        // 第一步：初始化WiFi模块（iOS和Android都需要）
        uni.startWifi({
          success: () => {
            console.log('WiFi模块初始化成功')
            
            // 第二步：连接指定WiFi（iOS需11及以上版本支持）
        uni.connectWifi({
          SSID: ssid,
          password: password,
          success: (res) => {
            console.log('WiFi连接成功：', res)
                
                // 监听WiFi连接成功事件
                uni.onWifiConnected((wifiRes) => {
                  console.log('WiFi已连接事件触发：', wifiRes)
                })
                
            resolve(res)
              },
              fail: (error) => {
                console.error('connectWifi失败：', error)
                console.error('错误码：', error.errCode, '错误信息：', error.errMsg)
                
                // 针对不同错误码给出详细提示
                let errorMessage = '连接WiFi失败'
                if (error.errCode === 12000) {
                  errorMessage = '未先调用 startWifi 接口'
                } else if (error.errCode === 12001) {
                  errorMessage = '当前系统不支持WiFi功能'
                } else if (error.errCode === 12002) {
                  errorMessage = 'WiFi密码错误'
                } else if (error.errCode === 12005) {
                  errorMessage = 'Android特有，未打开WiFi开关'
                } else if (error.errCode === 12007) {
                  errorMessage = '用户拒绝授权连接WiFi'
                } else if (error.errCode === 12010) {
                  errorMessage = 'iOS特有，系统版本低于iOS 11'
                } else if (error.errCode === 12013) {
                  errorMessage = '系统保存的WiFi配置过期'
                } else {
                  errorMessage = error.errMsg || '连接失败，请重试'
                }
                
                error.message = errorMessage
                reject(error)
              }
            })
          },
          fail: (error) => {
            console.error('startWifi失败：', error)
            console.error('错误码：', error.errCode, '错误信息：', error.errMsg)
            
            let errorMessage = '初始化WiFi模块失败'
            if (error.errCode === 12001) {
              errorMessage = '当前系统不支持WiFi功能'
            } else if (error.errCode === 12007) {
              errorMessage = '用户拒绝授权WiFi'
            } else {
              errorMessage = error.errMsg || '初始化失败，请重试'
            }
            
            error.message = errorMessage
            reject(error)
          }
        })
      })
    },
    
    // 跳转到手机验证页面
    gotoPhoneVerification() {
      // 获取用户信息进行微信授权
      uni.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          console.log('获取用户信息成功：', res)
          const userInfo = res.userInfo
          
          // 跳转到手机验证页面
          uni.navigateTo({
            url: `/pages/wifi/phone/index?deviceId=${this.deviceId}&sessionId=${this.sessionId}&userInfo=${encodeURIComponent(JSON.stringify(userInfo))}`
          })
        },
        fail: (error) => {
          console.error('获取用户信息失败：', error)
          // 即使获取用户信息失败，也允许继续流程
          uni.navigateTo({
            url: `/pages/wifi/phone/index?deviceId=${this.deviceId}&sessionId=${this.sessionId}`
          })
        }
      })
    },

    // 复制密码
    copyPassword() {
      if (!this.wifiList[0] || !this.wifiList[0].password) {
        uni.showToast({
          title: '没有密码可复制',
          icon: 'none'
        })
        return
      }
      
      uni.setClipboardData({
        data: this.wifiList[0].password,
        success: function () {
          uni.showToast({
            title: '密码已复制',
            icon: 'success'
          })
        },
        fail: function (error) {
          console.error('复制密码失败：', error)
          uni.showToast({
            title: '复制失败',
            icon: 'error'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wifi-list-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 60rpx 40rpx 20rpx;
  position: relative;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 30rpx;
}

.back-icon {
  font-size: 32rpx;
  font-weight: bold;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.header-icons {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.icon-item {
  font-size: 36rpx;
}

.record-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
}

.welcome-area {
  text-align: center;
  padding: 40rpx;
}

.welcome-title {
  font-size: 36rpx;
  font-weight: 500;
  opacity: 0.9;
}

.main-connect-area {
  display: flex;
  justify-content: center;
  padding: 40rpx;
  margin-bottom: 40rpx;
}

.connect-btn {
  width: 500rpx;
  height: 160rpx;
  background: linear-gradient(135deg, #ff9a00 0%, #ff6b00 100%);
  border: none;
  border-radius: 80rpx;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 0, 0.4);
  
  &::after {
    border: none;
  }
}

.btn-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.btn-text {
  font-size: 42rpx;
  font-weight: bold;
  margin-bottom: 4rpx;
}

.btn-subtext {
  font-size: 26rpx;
  opacity: 0.9;
}

.wifi-icon {
  font-size: 50rpx;
}

.wifi-list {
  background: #fff;
  border-radius: 40rpx 40rpx 0 0;
  margin-top: 40rpx;
  min-height: 60vh;
  padding: 40rpx;
  color: #333;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.list-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.refresh-btn {
  width: 60rpx;
  height: 60rpx;
  background: #f5f5f5;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.wifi-items {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.wifi-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #f8f9fa;
  border-radius: 20rpx;
  border: 2rpx solid transparent;
  
  &:active {
    background: #e9ecef;
    border-color: #1890ff;
  }
}

.wifi-info {
  flex: 1;
}

.wifi-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
}

.wifi-details {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.signal-strength {
  font-size: 24rpx;
  color: #52c41a;
}

.wifi-security {
  font-size: 24rpx;
  color: #999;
}

.wifi-actions {
  margin-left: 20rpx;
}

.action-btn {
  padding: 16rpx 32rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  border: none;
  
  &::after {
    border: none;
  }
  
  &:disabled {
    opacity: 0.6;
  }
}

.connect-btn-small {
  background: #1890ff;
  color: #fff;
}

.note-area {
  padding: 20rpx 40rpx;
  font-size: 24rpx;
  opacity: 0.7;
}

/* New styles for the simplified layout */
.wifi-info-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  background: #fff;
  border-radius: 40rpx;
  margin: 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  color: #333;
}

.wifi-icon-area {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.wifi-signal-icon {
  font-size: 60rpx;
  margin-right: 20rpx;
  color: #52c41a;
}

.wifi-name-display {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.wifi-actions-area {
  display: flex;
  gap: 20rpx;
  width: 100%;
  justify-content: center;
}

.action-button {
  flex: 1;
  padding: 20rpx 30rpx;
  border-radius: 30rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  &::after {
    border: none;
  }
  
  &:disabled {
    opacity: 0.6;
  }
}

.copy-button {
  background: #1890ff;
  color: #fff;
}

.connect-button {
  background: linear-gradient(135deg, #ff9a00 0%, #ff6b00 100%);
  color: #fff;
}

.loading-area {
  text-align: center;
  padding: 40rpx;
  color: #fff;
}

.loading-text {
  font-size: 36rpx;
  font-weight: 500;
  opacity: 0.9;
}

.error-area {
  text-align: center;
  padding: 40rpx;
  color: #fff;
}

.error-text {
  font-size: 36rpx;
  font-weight: 500;
  opacity: 0.9;
}

.retry-button {
  margin-top: 20rpx;
  padding: 20rpx 40rpx;
  border-radius: 30rpx;
  font-size: 32rpx;
  background: #fff;
  color: #1890ff;
  border: 2rpx solid #fff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  &::after {
    border: none;
  }
}

.ad-area {
  margin-top: 40rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 20rpx;
  color: #333;
}

.ad-content {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.ad-icon {
  font-size: 40rpx;
}

.ad-text {
  display: flex;
  flex-direction: column;
}

.ad-title {
  font-size: 32rpx;
  font-weight: bold;
}

.ad-subtitle {
  font-size: 24rpx;
  opacity: 0.8;
}

.ad-brand {
  font-size: 28rpx;
  font-weight: bold;
  color: #1890ff;
  margin-top: 10rpx;
}

.debug-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10rpx;
  font-size: 24rpx;
  opacity: 0.8;
  text-align: left;
  
  text {
    display: block;
    margin: 5rpx 0;
    word-break: break-all;
  }
}
</style> 